package cn.itsource.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: Jason
 * @Date: 2022/9/4 21:10
 */
@Component
@Slf4j
public class SmsConsumer {

    @RabbitListener(queues = "sms_queue")
    public void sendSms(Message message, Channel channel){
        String msg = new String(message.getBody());
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String msgContent = jsonObject.get("msg").toString();//发送短信内容
        String phone = jsonObject.get("phone").toString();//手机号
        log.info("消费者SmsConsumer监听到消息：{}", new String(message.getBody()));
        //处理业务代码
        //调用第三方接口发短信即可
        log.info("营销短信发送成功了");

        //手动ACK
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
        }
    }
}
